// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import {
    L2EProtocol,
    S2CProtocol
} from "../proto/ELProtocol";

import {
    loadImage,
    readStorage,
    saveStorage,
    simpleNum
} from "../utils/CommonUtils";

import {
    NotificationCenter 
} from "../utils/NotificationCenter";

const {ccclass, property} = cc._decorator;
const musicRes = ['button_shengyin_yinyuekai', 'button_shengyin_yinyueguan'];
const soundRes = ['button_shengyin_yinxiaokai', 'button_shengyin_yinxiaoguan'];
@ccclass
export default class NewClass extends cc.Component {
    @property(cc.Prefab)
    rankLayer: cc.Prefab = null;

    @property(cc.Prefab)
    rewardLayer: cc.Prefab = null;

    @property(cc.Prefab)
    dailyLayer: cc.Prefab = null;

    @property(cc.Prefab)
    trmbLayer: cc.Prefab = null;

    @property(cc.Prefab)
    helpLayer: cc.Prefab = null;

    @property(cc.Prefab)
    popTip: cc.Prefab = null;

    @property(cc.Prefab)
    msgBox: cc.Prefab = null;

    private showBanner: boolean = false;
    private myIcon: cc.Sprite = null;
    private myName: cc.Label = null;
    private trmbLabel: cc.Label = null;
    private blCountLabel: cc.Label = null;
    private soundOpBg: cc.Node = null;
    private openMusic: number = 1;
    private openSound: number = 1;
    private musicBtnBack: cc.Sprite = null;
    private soundBtnBack: cc.Sprite = null;

    private showSoundOption: boolean = false;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        NotificationCenter.Instance.on("openReward", this.openReward, this);
        NotificationCenter.Instance.on("pop_tips", this.popSimpleTip, this);
        NotificationCenter.Instance.on(S2CProtocol.s2c_req_adcode, this.showAd, this);
        NotificationCenter.Instance.on(L2EProtocol.l2e_req_wx_login, this.showReqWxLogin, this);
        NotificationCenter.Instance.on(L2EProtocol.l2e_refresh_rank, this.openRank, this);
        NotificationCenter.Instance.on(L2EProtocol.l2e_update_nickname, this.updateNickname, this);
        NotificationCenter.Instance.on(L2EProtocol.l2e_update_headIcon, this.updateHeadIcon, this);
        NotificationCenter.Instance.on(L2EProtocol.l2e_update_trmb, this.updateTrmb, this);
    }
    
    onDestroy() {
        NotificationCenter.Instance.off("openReward", this.openReward, this);
        NotificationCenter.Instance.off("pop_tips", this.popSimpleTip, this);
        NotificationCenter.Instance.off(S2CProtocol.s2c_req_adcode, this.showAd, this);
        NotificationCenter.Instance.off(L2EProtocol.l2e_req_wx_login, this.showReqWxLogin, this);
        NotificationCenter.Instance.off(L2EProtocol.l2e_refresh_rank, this.openRank, this);
        NotificationCenter.Instance.off(L2EProtocol.l2e_update_nickname, this.updateNickname, this);
        NotificationCenter.Instance.off(L2EProtocol.l2e_update_headIcon, this.updateHeadIcon, this);
        NotificationCenter.Instance.on(L2EProtocol.l2e_update_trmb, this.updateTrmb, this);
        
    }

    start () {
        let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
        let userInfo = logicCenter.getUserInfo();

        this.trmbLabel = cc.find('btn_exchange/label_trmb', this.node).getComponent(cc.Label);
        this.trmbLabel.string = simpleNum(userInfo.trmb);
        this.blCountLabel = cc.find('im_bg_bl/label_bl', this.node).getComponent(cc.Label);
        this.blCountLabel.string = simpleNum(userInfo.bl);

        cc.find('im_head_icon/im_icon_kuang/label_id', this.node).getComponent(cc.Label).string = "id:"+userInfo.playerId;
        this.myIcon = cc.find('im_head_icon', this.node).getComponent(cc.Sprite);
        this.myName = cc.find('im_head_icon/im_icon_kuang/label_name', this.node).getComponent(cc.Label);

        if (userInfo.headIcon != null && userInfo.headIcon.lenghth > 11) {
            let self = this;
            loadImage(userInfo.headIcon, (spriteFrame) => {
                self.myIcon.spriteFrame = spriteFrame;
            });  
        }

        if (userInfo.nickName == null) {
            userInfo.nickName = "无名氏";
        }
        this.myName.string = userInfo.nickName;

        this.soundOpBg = cc.find('option_node/im_bg', this.node);
        this.soundOpBg.y = -230;

        this.openMusic = Number(readStorage('open_music') || 0);
        this.openSound = Number(readStorage('open_sound') || 0);
        if (this.openMusic == 0) {
            this.openMusic = 1;
        }
        if (this.openSound == 0) {
            this.openSound = 1;
        }
        this.soundBtnBack = cc.find('option_node/im_bg/btn_sound/Background', this.node).getComponent(cc.Sprite);
        this.musicBtnBack = cc.find('option_node/im_bg/btn_music/Background', this.node).getComponent(cc.Sprite);

        let self = this;
        cc.resources.load('image/'+soundRes[this.openSound-1], cc.SpriteFrame, (err: Error, spriteFrame: cc.SpriteFrame) => {
            if (err) {
                console.log(err);
                return;
            }
            self.soundBtnBack.spriteFrame = spriteFrame;
        });
        cc.resources.load('image/'+musicRes[this.openMusic-1], cc.SpriteFrame, (err: Error, spriteFrame: cc.SpriteFrame) => {
            if (err) {
                console.log(err);
                return;
            }
            self.musicBtnBack.spriteFrame = spriteFrame;
        });
        this.switchMusic();
    }

    // update (dt) {}

    public clickStart() {
        cc.director.loadScene("game");
    }

    public clickSoundOp() {
        this.showSoundOption = !this.showSoundOption;
        let targetY = 20;
        let dur = 0.5;
        if (this.showSoundOption == false) {
            targetY = -230;
            dur = 0.5*(this.soundOpBg.y+230)/250;
        }else{
            dur = -0.5*(this.soundOpBg.y-20)/250;

        }
        this.soundOpBg.stopAllActions();
        cc.tween(this.soundOpBg)
            .to(dur, {y: targetY})
            .start();
    }

    public clickMusic() {
        this.openMusic++;
        if (this.openMusic == 3) {
            this.openMusic = 1;
        }

        saveStorage('open_music', this.openMusic);

        let self = this;
        cc.resources.load('image/'+musicRes[this.openMusic-1], cc.SpriteFrame, (err: Error, spriteFrame: cc.SpriteFrame) => {
            if (err) {
                console.log(err);
                return;
            }
            self.musicBtnBack.spriteFrame = spriteFrame;
        });
        this.switchMusic();
    }

    public clickSound() {
        this.openSound++;
        if (this.openSound == 3) {
            this.openSound = 1;
        }

        saveStorage('open_sound', this.openSound);

        let self = this;
        cc.resources.load('image/'+soundRes[this.openSound-1], cc.SpriteFrame, (err: Error, spriteFrame: cc.SpriteFrame) => {
            if (err) {
                console.log(err);
                return;
            }
            self.soundBtnBack.spriteFrame = spriteFrame;
        });
    }

    private switchMusic() {
        let music = this.node.getComponent(cc.AudioSource);
        if (this.openMusic == 2) {
            music.stop();
        }else{
            music.loop = true;
            music.play();
        }
    }

    public clickHelp() {
        let layer = cc.instantiate(this.helpLayer);
        layer.parent = this.node;
    }

    public clickRank() {
        NotificationCenter.Instance.emit("requestworldRank", 0);
    }
    
    public openRank(data: any) {
        let layer = cc.instantiate(this.rankLayer);
        layer.parent = this.node;
        layer.getComponent('Rank').refreshList(data);
    }

    public clickTrmb() {
        let layer = cc.instantiate(this.trmbLayer);
        layer.parent = this.node;
    }

    public clickShare() {

    }

    public clickDaily() {
        let layer = cc.instantiate(this.dailyLayer);
        layer.parent = this.node;
    }

    public clickRewardAd() {
        if (!cc.sys.isNative) {
            return;
        }
        jsb.reflection.callStaticMethod("com/bbl/pineapple/JniHelper", "showRewardAd", "()V");
    }

    public clickBannerAd() {
        if (!cc.sys.isNative) {
            return;
        }
        this.showBanner = !this.showBanner;
        if (this.showBanner) {
            jsb.reflection.callStaticMethod("com/bbl/pineapple/JniHelper", "showBannerAd", "()V");
        }else{
            jsb.reflection.callStaticMethod("com/bbl/pineapple/JniHelper", "hideBannerAd", "()V");
        }
    }

    public updateNickname(name: string) {

        if (name == null) {
            name = "无名氏";
        }
        this.myName.string = name;
    }

    public updateHeadIcon(icon: string) {
        if (icon != null && icon.length > 11) {
            let self = this;
            loadImage(icon, (spriteFrame) => {
                self.myIcon.spriteFrame = spriteFrame;
            });  
        }
    }

    private updateTrmb(value: number) {
        this.trmbLabel.string = String(value);
    }

    public showAd(data: any) {
        if (cc.sys.WECHAT_GAME == cc.sys.platform) {
            if (data.adType == 1) {
                NotificationCenter.Instance.emit("requestFinishAd");
            }else{
                this.tryVideoAd();
            }
        }else if (cc.sys.isNative) {
            jsb.reflection.callStaticMethod("com/bbl/pineapple/JniHelper", "showRewardAd", "()V");
        }else {
            //todo 广告，暂时模拟onFinish
            let t = cc.tween;
            t(this.node)
                .delay(15)
                .call(() => {
                    NotificationCenter.Instance.emit("requestFinishAd");
                })
                .start();
        }
    }

    private tryVideoAd() {
        // let self = this;
        // this.videoAds[this.videoIndex].load()
        //     .then(() => {
        //         console.log('激励视频加载成功');
        //         this.videoAds[this.videoIndex].show().then(() => {
        //             self.videoValid = true;
        //             console.log('激励视频 广告显示成功');
        //         })
        //         .catch(err => {
        //             console.log('激励视频 广告显示失败',err);
        //             self.videoValid = false;
        //             this.videoIndex++;
        //             if (this.videoIndex >= this.videoAds.length) {
        //                 let popData = <TIP_INFO>{};
        //                 popData.dur = 0.6;
        //                 popData.type = 2;
        //                 popData.tip = '广告还没准备好，请稍后再试！';
        //                 NotificationCenter.Instance.emit('pop_tips', popData);
        //                 this.videoIndex = 0;
        //             }else{
        //                 this.tryVideoAd();
        //             }
        //         })
        //     })
        //     .catch(err => {
        //         console.log('激励视频加载失败', err);
        //         self.videoValid = false;
        //         this.videoIndex++;
        //         if (this.videoIndex >= this.videoAds.length) {
        //             let popData = <TIP_INFO>{};
        //             popData.dur = 0.6;
        //             popData.type = 2;
        //             popData.tip = '广告还没准备好，请稍后再试！';
        //             NotificationCenter.Instance.emit('pop_tips', popData);
        //             this.videoIndex = 0;
        //         }else{
        //             this.tryVideoAd();
        //         }
        //     });
    }

    private popSimpleTip(data: any) {
        let tip = cc.instantiate(this.popTip);
        tip.getComponent('TipLogic').setupView(data.dur, data.type, data.resPath, data.count, data.tip);
        tip.parent = this.node;
    }

    public openReward(iconRes: string, txt: string, scale: number = 1) {
        let layer = cc.instantiate(this.rewardLayer);
        layer.parent = this.node;
        layer.getComponent('RewardLogic').setupView(iconRes, txt, scale);
    }

    private showReqWxLogin() {
        let box = cc.instantiate(this.msgBox);
        let confirm = new cc.Component.EventHandler();
        confirm.target = this.node;
        confirm.component = 'Hall';
        confirm.handler = 'wxLogin';

        let cancel = new cc.Component.EventHandler();
        cancel.target = this.node;
        cancel.component = 'Hall';
        cancel.handler = 'closeMsg';

        box.getComponent('MsgBoxLogic').setupView('登录微信，方可开启此功能。', 3, confirm, cancel);
        box.parent = this.node;
    }

    public wxLogin() {
        NotificationCenter.Instance.emit("close_msgbox");
        jsb.reflection.callStaticMethod("com/bbl/pineapple/JniHelper", "wxLogin", "()V");
    }

    public closeMsg() {
        NotificationCenter.Instance.emit("close_msgbox");
    }
}